<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			body {
				margin: 0px;
				padding: 0px;
			}

			svg {
				background-color: #008000;
			}
		</style>
	</head>
	<body>
		<svg id="s" version="1.1" baseProfile="full" width="100%" xmlns="http://www.w3.org/2000/svg">

			<!-- <rect id='table1' class='table-rect' width="100" height="160" x='300' y='100'
				style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" />

			<rect id='table1-right' componentType='startConnectPoint' class='table-rect' width="10" height="10" x='400'
				y='180' style="fill:#FFFFFF;stroke-width:1;stroke:rgb(0,0,0)" />



			<rect id='table2' class='table-rect' width="100" height="160" x='600' y='400'
				style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" />
			<rect id='table2-left' componentType='endConnectPoint' class='table-rect' width="10" height="10" x='590'
				y='480' style="fill:#FFFFFF;stroke-width:1;stroke:rgb(0,0,0)" /> -->

		</svg>
	</body>
</html>
<script src="index.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	var SVG_NS = "http://www.w3.org/2000/svg";
	var overConnectPoint = null;

	function stopPropagation(e) {
		e = e || window.event;
		if (e.stopPropagation) { //W3C阻止冒泡方法 
			e.stopPropagation();
		} else {
			e.cancelBubble = true; //IE阻止冒泡方法 
		}
	}
	window.onload = function() {
		let clientHeight = window.innerHeight;
		document.getElementById("s").style.height = window.innerHeight + "px"
	}

	let svg = document.getElementById("s")

	function createPolyline(x, y, startId) {
		var polyline = document.createElementNS(SVG_NS, 'polyline')
		polyline.setAttribute('points', x + "," + y)
		polyline.setAttribute("marker-end", "url(#markerArrow)")
		polyline.setAttribute("componentType", "connectLine");
		polyline.setAttribute("startId", startId)
		polyline.setAttribute("style", "fill:none;stroke:#000;stroke-width:2");
		polyline.setAttribute("class", "table-rect-connect-line")
		//监听移入事件
		polyline.addEventListener("mouseover", function(e) {
			window.ee = e;
			e.target.style.strokeWidth = "4"
		}, false)
		//鼠标移除事件
		polyline.addEventListener("mouseout", function(e) {
			e.target.style.strokeWidth = "2"
		}, false)

		return polyline;
	}

	function getConnectLineByConnectPoint(cpId) {
		let ps = document.getElementsByTagName("polyline")
		for (var i = 0; i < ps.length; i++) {
			let p = ps[i]
			let startId = p.getAttribute("startId")
			let endId = p.getAttribute("endId")
			if (cpId == startId || cpId == endId) {
				return p;
			}
		}
		return null;
	}

	/**
	 * 垂直线段算法
	 * @param {Object} x1
	 * @param {Object} y1
	 * @param {Object} x2
	 * @param {Object} y2
	 * @param {Object} sl
	 * @param {Object} el 计算两条线段的
	 */
	function zhexian(x1, y1, x2, y2, sl, el) {
		
		if (sl == "top") {
			let px1 = x1;
			let py1 = y1;
			
			let px2 = px1;
			let py2 = y2;
			
			let px3 = x2;
			let py3 = py2
			let px4 = x2;
			let py4 = y2
			return px1 + "," + py1 + " " + px2 + "," + py2 + " " + px3 + "," + py3;
		}

		if (sl == "bottom") {
			let px1 = x1;
			let py1 = y1;
			
			let px2 = px1;
			let py2 = y2;
			
			let px3 = x2;
			let py3 = py2
			let px4 = x2;
			let py4 = y2
			return px1 + "," + py1 + " " + px2 + "," + py2 + " " + px3 + "," + py3;
		}


		let px1 = x1;
		let py1 = y1;

		let px2 = x2 - ((x2 - x1) / 2);
		let py2 = y1;

		let px3 = px2;
		let py3 = y2

		let px4 = x2;
		let py4 = y2
		return px1 + "," + py1 + " " + px2 + "," + py2 + " " + px3 + "," + py3 + " " + px4 + "," + py4;
	}

	/**
	 * 创建表模型
	 * @param {Object} x 位置y
	 * @param {Object} y 位置x
	 * @param {Object} id模型的id
	 */
	function createTableModel(x, y, id) {
		let rect = document.createElementNS(SVG_NS, "rect")
		rect.style = "fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"
		rect.setAttribute("class", "table-rect")
		rect.setAttribute("width", "100")
		rect.setAttribute("height", "160")
		rect.setAttribute("x", x)
		rect.setAttribute("y", y);
		rect.id = id;
		rect.addEventListener("mousedown", function(e) {
			let tableId = e.target.id;
			let tableConnectPointId = tableId + "-" + "right";
			let tableConnectPoint = document.getElementById(tableConnectPointId);
			//根据连接点获取连接线
			let cp = getConnectLineByConnectPoint(tableConnectPointId)
			//偏移量
			let offsetX = e.clientX - rect.getAttribute("x");
			let offsetY = e.clientY - rect.getAttribute("y");
			/**
			 * 鼠标移动事件
			 * @param {Object} e2
			 */
			function handleMove(e2) {
				//获取连接线对象
				// let duan = zhexian(sx, sy, e2.clientX, e2.clientY)
				// polyline.setAttribute("points", duan);
				let targetX = e2.clientX - offsetX;
				let targetY = e2.clientY - offsetY;
				rect.setAttribute("x", targetX)
				rect.setAttribute("y", targetY);
				//移动的连接点
				let rects = document.getElementsByTagName("rect")
				for (var i = 0; i < rects.length; i++) {
					let r = rects[i]
					let cpId = r.getAttribute("tableId")
					if (tableId == cpId) {
						let connectPointId = r.id;
						let l = r.getAttribute("connectPointLocal")
						let position = calculateConnectPointCoord(targetX, targetY, l);
						r.setAttribute("x", position.x);
						r.setAttribute("y", position.y);
						//重新绘制连接线
						reWriteConnectLine(connectPointId, position.x, position.y)
					}

				}
			}
			document.body.addEventListener('mousemove', handleMove, false);

			function finishMove(e3) {
				document.body.removeEventListener('mousemove', handleMove, false);
				svg.removeEventListener('mouseup', finishMove, false);
			}

			//鼠标松开事件
			rect.addEventListener('mouseup', finishMove, false);
		})
		svg.appendChild(rect)
		//创建连接点
		let left = createTableConnectPoint(id, x, y, "left");
		let right = createTableConnectPoint(id, x, y, "right");
		let top = createTableConnectPoint(id, x, y, "top");
		let bottom = createTableConnectPoint(id, x, y, "bottom");
		svg.appendChild(left);
		svg.appendChild(right);
		svg.appendChild(top);
		svg.appendChild(bottom);
	}

	/**
	 * 重画连接线
	 * @param {Object} cpId 连接点id
	 * @param {Object} x 连接点的最新位置
	 * @param {Object} y
	 */
	function reWriteConnectLine(cpId, x, y) {
		let lines = document.getElementsByClassName("table-rect-connect-line")
		for (var i = 0; i < lines.length; i++) {
			let line = lines[i]
			let startId = line.getAttribute("startId")
			let endId = line.getAttribute("endId")
			if (startId == cpId) {
				//重画以此点为起点的线段
				let points = line.getAttribute("points")
				let endPosition = getLastForPoints(points)
				let newPoints = zhexian(x, y, endPosition.x, endPosition.y)
				console.log('轨迹：', newPoints)
				line.setAttribute("points", newPoints);
			}

			if (endId == cpId) {
				//重画以此点为起点的线段
				let points = line.getAttribute("points")
				let firstPosition = getFirstForPoints(points)
				let newPoints = zhexian(firstPosition.x, firstPosition.y, x, y)
				console.log('轨迹：', newPoints)
				line.setAttribute("points", newPoints);
			}
		}
	}


	/**
	 * 创建连接点
	 * @param {Object} tx table模型的位置，用于计算连接点的位置
	 * @param {Object} ty table模型的位置，用于计算连接点的位置
	 * @param {Object} l 连接点的位置，可选值：top、bottom、left、right
	 */
	function createTableConnectPoint(tableId, tx, ty, l) {
		let rect = document.createElementNS(SVG_NS, "rect")
		rect.style = "fill:#FFFFFF;stroke-width:1;stroke:rgb(0,0,0)"
		rect.setAttribute("class", "table-rect-connect-point")
		rect.setAttribute("width", "10")
		rect.setAttribute("height", "10")
		rect.setAttribute("connectPointLocal", l);
		rect.setAttribute("tableId", tableId);
		//监听事件
		rect.addEventListener("mousedown", function(e) {
			let startId = rect.attributes.id.value;
			var polyline = createPolyline(e.clientX, e.clientY, startId)
			svg.appendChild(polyline)
			var sx = e.clientX,
				sy = e.clientY
			/**
			 * 鼠标移动事件
			 * @param {Object} e2
			 */
			function handleMove(e2) {
				let duan = zhexian(sx, sy, e2.clientX, e2.clientY, l)
				polyline.setAttribute("points", duan);
				let endId = overConnectPoint.target.id;
				polyline.setAttribute("endId", endId)

				//监听rect的鼠标悬浮事件
				// document.getElementById("table1").addEventListener("mouseover", function(e4) {
				// 	console.log("鼠标移动到矩形上方了")
				// }, false)
			}
			document.body.addEventListener('mousemove', handleMove, false);

			/**
			 * 鼠标松开处理
			 * @param {Object} e3
			 */
			function finishMove(e3) {
				document.body.removeEventListener('mousemove', handleMove, false);
				svg.removeEventListener('mouseup', finishMove, false);
			}

			//鼠标松开事件
			svg.addEventListener('mouseup', finishMove, false);
		}, false)

		/**
		 * 连接点的鼠标移入事件
		 * @param {Object} e
		 */
		rect.addEventListener("mouseover", function(e) {
			overConnectPoint = e;
		})

		let coord = calculateConnectPointCoord(tx, ty, l);
		rect.setAttribute("x", coord.x)
		rect.setAttribute("y", coord.y);
		rect.id = tableId + "-" + l
		return rect;
	}

	function calculateConnectPointCoord(tx, ty, l) {
		let x, y;
		//计算x和y的位置咯
		if (l == "top") {
			x = tx + 45
			y = ty - 10;
		}
		if (l == "bottom") {
			x = tx + 45;
			y = ty + 160;
		}
		if (l == "left") {
			x = tx - 10;
			y = ty + 80;
		}
		if (l == "right") {
			x = tx + 100
			y = ty + 80;
		}
		return {
			x: x,
			y: y
		};
	}

	//初始化表模型
	createTableModel(300, 100, "table1")
	createTableModel(600, 400, "table2")
	createTableModel(800, 200, "table3")
</script>
